package groovyuno

import com.sun.star.beans.XPropertySetInfo
import com.sun.star.lang.XSingleServiceFactory
import com.sun.star.reflection.XIdlClass
import com.sun.star.reflection.XIdlReflection
import com.sun.star.script.XInvocation
import com.sun.star.uno.UnoRuntime

protected class UNOExpander {

	def static void expand() {
		Object.metaClass.uno << { t -> UnoRuntime.queryInterface(t, delegate) }

		Object.metaClass.isProxy << {
			def refl = UNO.createUNOService("com.sun.star.reflection.CoreReflection").uno(XIdlReflection)
			refl.getType(delegate).uno(XIdlClass).name == "com.sun.star.uno.XInterface"
		}

		com.sun.star.lib.uno.Proxy.metaClass.getUnoProperties << {
			delegate.getPropertySetInfo().uno(XPropertySetInfo).getProperties()
		}

		com.sun.star.lib.uno.Proxy.metaClass.methodMissing = { name, args ->
			def ssf = UNO.createUNOService("com.sun.star.script.Invocation").uno(XSingleServiceFactory)
			XInvocation invoc = ssf.createInstanceWithArguments([delegate]as Object[]).uno(XInvocation)
			short[][] out_index = new short[1][]
			Object[][] out_param = new Object[1][]
			def ret = invoc.invoke(name, args as Object[], out_index, out_param)
			return ret.getObject()
		}

		com.sun.star.lib.uno.Proxy.metaClass.getProperty = { String name -> delegate.getPropertyValue(name) }
		com.sun.star.lib.uno.Proxy.metaClass.setProperty = { String name, Object value -> delegate.setPropertyValue(name, value) }

		com.sun.star.lib.uno.Proxy.metaClass.getAt = { String name -> delegate.getByName(name) }
		//		com.sun.star.lib.uno.Proxy.metaClass.putAt = { String pname, Object newValue -> delegate.setPropertyValue(pname, newValue) }
		com.sun.star.lib.uno.Proxy.metaClass.getAt = { int x -> delegate.getByIndex(x) }
	}
}
